package com.wf.classRoomTest;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashSet;

public class HashSetIndexGetter {

    public static void main(String[] args) {
        try {
            // 创建HashSet对象
            HashSet<String> set = new HashSet<>();
            set.add("apple");
            set.add("banana");
            set.add("orange");

            // 获取HashSet内部table字段
            Field tableField = HashSet.class.getDeclaredField("map");
            tableField.setAccessible(true); // 设置为可访问



            Field table1 = tableField.getClass().getDeclaredField("DEFAULT_INITIAL_CAPACITY");



            // 获取HashSet内部数组
            Object[] table = (Object[]) table1.get(set);

            // 遍历数组，查找元素的下标值
            for (int i = 0; i < table.length; i++) {
                Object entry = table[i];
                if (entry != null) {
                    System.out.println("Index " + i + ": " + entry);
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
